package com.game.fg.service;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.java_websocket.WebSocket;

import java.util.Dictionary;
import java.util.Enumeration;
import java.util.Hashtable;

public class FGUserManager {
    private static Logger logger = LogManager.getLogger(FGUserManager.class.getName());
    //玩家map
    private Dictionary<WebSocket, FGUser> userMap = new Hashtable<WebSocket, FGUser>();

    //添加玩家
    void addUser(FGUser user) {
        userMap.put(user.getWs(), user);
    }

    //获取玩家
    FGUser getUser(WebSocket ws) {
        return userMap.get(ws);
    }

    FGUser getUser(int uid) {
        Enumeration e = userMap.elements();
        while (e.hasMoreElements()) {
            FGUser user = (FGUser) e.nextElement();
            if (user.getUid() == uid) {
                return user;
            }
        }
        return null;
    }

    void removeUser(WebSocket ws, String reason) {
        FGUser user = userMap.get(ws);
        if (user != null) {
            logger.debug(String.format("移除玩家 uid:%d money:%d reason:%s", user.getUid(), user.getMoney(), reason));
            if (reason.equals("socket断开连接")) {
                //玩家离线回写一次数据
                AuthServer.getInstance().writeUserData(user);
                //删除在线状态
                AuthServer.getInstance().DeleteOnlineState(user.getUid());
                //MQ日志
                MQServer.getInstance().onUserLeave(user);
            }

            if (ws.isOpen()) {
                ws.close();
            }
            userMap.remove(ws);
        }
    }

    void removeUser(int uid, String reason) {
        Enumeration e = getUserMap().elements();
        while (e.hasMoreElements()) {
            FGUser user = (FGUser) e.nextElement();
            if (user.getUid() == uid) {
                removeUser(user.getWs(), reason);
                break;
            }
        }

    }

    Dictionary<WebSocket, FGUser> getUserMap() {
        return userMap;
    }

    private static FGUserManager fgUM = new FGUserManager();

    public static FGUserManager getInstance() {
        return fgUM;
    }
}
